import React, { useState, useEffect, useRef } from 'react';
import Input from '@/components/Input';
import Dialog from './components/dialog';
import { chatMessageType, chatContextType } from '@/types/chat';
import { v4 as uuidv4 } from 'uuid';
// import { askGPTPOST } from '@/api/fastgpt/basechat';
import HistoryChatItems from './components/historyChatItems';
import IconLeft from '@/components/Icons/IconLeft';
import IconRight from '@/components/Icons/IconRight';
import classNames from 'classnames';
// import baseStreamDataFetch from '@/utils/fetchData/baseStreamDataFetch';
import { useSelector, useDispatch } from 'react-redux';
import { addDialogDetail } from '@/store/actions/chat';
import { useRouter } from 'next/router';
import askChatGPT from '@/utils/askGPT';

const Chat: React.FC = () => {
  const router = useRouter();
  const dispatch = useDispatch();

  const [textValue, setTextValue] = useState('');
  const [historyVisible, setHistoryVisible] = useState<boolean>(true);
  // const [inputDisabled, setInputDisabled] = useState<boolean>(false);
  const containerRef = useRef<HTMLDivElement | null>(null);
  const chatContexts = useSelector((state: any) => state.chat.chatContexts);
  const [chatContext, setChatContext] = useState<chatContextType>({
    chatid: '',
    title: '',
    context: [],
  });

  const [gptResponse, setGptResponse] = useState('');

  useEffect(() => {
    const newChatContext = { ...chatContext };
    if (newChatContext.context && newChatContext.context.length > 0) {
      newChatContext.context[newChatContext.context.length - 1].content = gptResponse;
    }
    scrollToBottom(containerRef);
  }, [gptResponse]);

  // view router change
  useEffect(() => {
    // console.log(router.query.id);
    if (router.query.id) {
      const foundIndex = chatContexts.findIndex((item: chatContextType) => item.chatid === router.query.id);
      if (foundIndex !== -1) {
        setChatContext(chatContexts[foundIndex]);
      } else {
        setChatContext({
          chatid: '',
          title: '',
          context: [],
        });
      }
    } else {
      setChatContext({
        chatid: '',
        title: '',
        context: [],
      });
    }

    // if from home page
    if (router.query.inputText) {
      const fromHomePageInput = router.query.inputText.toString();
      const userChat: chatMessageType = {
        id: uuidv4(),
        role: 'USER',
        content: fromHomePageInput,
      };

      if (chatContext) {
        const newChatContext = { ...chatContext };
        newChatContext.context.push(userChat);
        setChatContext(newChatContext);
      }
    }
  }, [router]);

  // 处理键盘按下事件
  const handleKeyDown = (event: React.KeyboardEvent<HTMLTextAreaElement>) => {
    if (event.key === 'Enter') {
      if (event.shiftKey) {
        // event.preventDefault(); // 阻止默认行为，比如换行
      } else {
        // Enter 按下
        event.preventDefault();
        // 用户对话
        const userChat: chatMessageType = {
          id: uuidv4(),
          role: 'USER',
          content: textValue,
        };
        const botChat: chatMessageType = {
          id: uuidv4(),
          role: 'BOT',
          content: 'AI 正在思考...',
        };
        const newChatContext = { ...chatContext };
        newChatContext.context.push(userChat);
        newChatContext.context.push(botChat);
        if (newChatContext.chatid === '' || newChatContext.chatid === undefined) {
          newChatContext.chatid = uuidv4();
        }
        if (newChatContext.title === '' || newChatContext.title === undefined) {
          newChatContext.title = textValue.substring(0, 10);
        }
        setChatContext(newChatContext);
        // 重置输入框
        setTextValue('');
        // 发送请求
        askChatGPT(textValue, setGptResponse);
        dispatch(addDialogDetail(newChatContext));
        if (!router.query.id) {
          router.push({ pathname: '/chat', query: { id: newChatContext.chatid } });
        }
      }
    }
  };

  const changeHistoryVisible = () => {
    setHistoryVisible(!historyVisible);
  };

  // 文本输入事件
  const handleTextChange = (event: React.ChangeEvent<HTMLTextAreaElement>) => {
    setTextValue(event.target.value);
  };

  return (
    <div className="flex h-full">
      {/* history list */}
      {historyVisible ? (
        <div className=" bg-white basis-1/6 border-r h-full">
          <HistoryChatItems className="h-5/6" />
        </div>
      ) : (
        <></>
      )}

      {/* dialog */}
      <div className={classNames('relative h-full', historyVisible ? 'basis-5/6' : 'w-full')}>
        {/* collapsed */}
        <div
          className={classNames(
            'absolute top-1/2  transform -translate-y-1/2 w-3.5 h-11 bg-white  border border-slate-300 pr-0.1 items-center',
            historyVisible ? 'rounded-lg -left-2' : 'rounded-r-lg left-0',
          )}
          onClick={changeHistoryVisible}
        >
          {historyVisible ? <IconLeft className="w-[0.75rem] h-10" /> : <IconRight className="w-[0.75rem] h-10 " />}
        </div>

        {/* chat */}
        <div ref={containerRef} id="dialogs" className=" h-5/6 overflow-auto scrollbar-hide ">
          {/* params */}
          {/* <div className="h-9 bg-slate-200"></div> */}
          <Dialog className="h-96" dialogList={chatContext.context} />
        </div>

        {/* input */}
        <div className="h-1/6 w-full flex items-center">
          <Input onKeyDown={handleKeyDown} value={textValue} onChange={handleTextChange} />
        </div>
      </div>
    </div>
  );
};

//滚动到底部
const scrollToBottom = (containerRef: any) => {
  if (containerRef.current) {
    containerRef.current.scrollTop = containerRef.current.scrollHeight;
  }
};

export default Chat;
